package com.zwq.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/hello")
public class HelloMvcController {
	
	@RequestMapping("/mvc")
	public String hellomvc() {
		return "hello";
	}
	
	//参数传递
	@RequestMapping("/param")
	public String helloparam(@RequestParam("id") String id) {
		System.out.println("id="+id);
		return "hello";
	}
	
	//路径参数传递，restful风格
	@RequestMapping("/param2/{cid}")
	public String helloparam2(@PathVariable("cid") String id) {
		System.out.println("id="+id);
		return "hello";
	}
	
	//传统HttpServletRequest使用
	@RequestMapping("/req")
	@ResponseBody //直接返回字符串
	public String req(HttpServletRequest request) {
		String id=request.getParameter("id");
		System.out.println("id="+id);
		return "success:"+id;
	}
	
	//路径作为参数返回对应的页面，如下面请求地址为:/admin?add, 返回add.jsp页面
	@RequestMapping(value="/admin",method=RequestMethod.GET,params="add")
	public String add() {
		
		return "admin/add";
		
		//此外，redirect:为重定向到另外一个请求路径,如下为重定向到/hello/mvc
		//return "redirect:mvc";
	}
	
	//文件上传
	@RequestMapping(value="/doupload",method=RequestMethod.POST)
	public String doupload(@RequestParam("file") MultipartFile file) throws IOException {
		
		if(!file.isEmpty()) {
			System.out.println("Process file"+file.getOriginalFilename());
			FileUtils.copyInputStreamToFile(file.getInputStream(), new File("D:\\"+System.currentTimeMillis()+file.getOriginalFilename()));
		}
		
		return "success";
	}
}
